package org.eclipse.moquette.parser.netty;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.CorruptedFrameException;
import io.netty.util.AttributeKey;
import org.eclipse.moquette.proto.messages.AbstractMessage;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by alex on 15-5-19.
 */
public class MQTTDecoder extends ByteToMessageDecoder {

    static final AttributeKey<Integer> PROTOCOL_VERSION = AttributeKey.valueOf("version");

    private final Map<Byte, DemuxDecoder> m_decoderMap = new HashMap<Byte, DemuxDecoder>();

    public MQTTDecoder() {
        m_decoderMap.put(AbstractMessage.CONNECT, new ConnectDecoder());
    }

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf in, List<Object> out) throws Exception {
        in.markReaderIndex();
        if (!Utils.checkHeaderAvailability(in)) {
            in.resetReaderIndex();
            return;
        }

        in.resetReaderIndex();

        byte messageType = Utils.readMessageType(in);

        DemuxDecoder decoder = m_decoderMap.get(messageType);
        if (decoder == null){
            throw new CorruptedFrameException("Can't find any suitable decoder for message type: " + messageType);
        }
        decoder.decode(channelHandlerContext, in ,out);
    }
}
